package top.lixunda.common.validate.validate;

import lombok.extern.slf4j.Slf4j;
import top.lixunda.common.validate.annotation.XumMinDate;
import top.lixunda.common.validate.core.ValidateError;
import top.lixunda.common.validate.exception.XumValidException;

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.format.DateTimeParseException;

/**
 * @author Xumda
 * @version time:2019/12/9 13:15
 */
@SuppressWarnings("Duplicates")
@Slf4j
public class MinDateValidate implements AnnotationValidate {

    private static final String DEFAULT_FORMAT = "yyyy-MM-dd HH:mm:ss";

    private static final String KEY_MIN = "min";

    private DateTimeFormatter formatter;

    private DateTimeFormatter paramFormatter;

    private DateTimeFormatter getFormatter(String format) {
        if (formatter == null) {
            synchronized (this) {
                if (formatter == null) {
                    formatter = "".equals(format) ? DateTimeFormatter.ofPattern(DEFAULT_FORMAT) :
                            DateTimeFormatter.ofPattern(format);
                }
            }
        }
        return this.formatter;
    }

    private DateTimeFormatter getParamFormatter(String paramFormat) {
        if (this.paramFormatter == null) {
            synchronized (this) {
                if (paramFormatter == null) {
                    paramFormatter = "".equals(paramFormat) ? DateTimeFormatter.ofPattern(DEFAULT_FORMAT) :
                            DateTimeFormatter.ofPattern(paramFormat);
                }
            }
        }
        return this.paramFormatter;
    }

    @Override
    public boolean support(Class annotationClass) {
        return XumMinDate.class.equals(annotationClass);
    }

    @Override
    public ValidateError valid(Annotation annotation, Field field, Object obj, Object value, AnnotationCacheValidate handler) {
        XumMinDate a = (XumMinDate) annotation;
        boolean isNull = (value == null || (value instanceof String && "".equals(value)));
        if (isNull) {
            return null;
        }
        int result;
        if (value instanceof String) {
            try {
                LocalDateTime time = LocalDateTime.parse((CharSequence) value, getParamFormatter(a.paramFormat()));
                LocalDateTime min = (LocalDateTime) handler.getCacheMap().get(KEY_MIN);
                log.debug("从缓存中获取maxDate的值 {}", min);
                if (min == null) {
                    min = LocalDateTime.parse(a.value(), getFormatter(a.format()));
                    handler.getCacheMap().put(KEY_MIN, min);
                }
                result = time.compareTo(min);
            } catch (DateTimeParseException e) {
                throw new XumValidException("解析时间格式错误");
            }
        } else {
            throw new XumValidException("注解MinDate不支持该格式参数");
        }

        // 返回结果
        return (a.include() ? result >= 0 : result > 0) ? null : new ValidateError(getErrorMessage(a.message(),
                field, String.valueOf(value), a.include()));
    }

    private String getErrorMessage(String message, Field field, String value, boolean include) {
        return "".equals(message)
                ? field.getName() + "应大于" + (include ? "等于" : "") + value
                : message.replaceAll("#value#", String.valueOf(value)).replaceAll("#name#", field.getName());
    }

}
